import type { Directive } from 'vue'
import { useReport } from '@/composables/hooks/useReport'
import { emailRegExp } from '@/utils/regex'

const tagName = 'A'
const hostList = ['https://', 'http://']
const hrefList = ['gitcode.com', 'gitcode.net']
const PrefixEmail = 'mailto:'

function queryTag(node: any): any {
  let parent = node
  if (parent.tagName === tagName) {
    return { isATag: true, node: parent }
  }
  else {
    while (parent.parentNode) {
      parent = parent.parentNode
      if (parent.tagName === tagName) {
        return { isATag: true, node: parent }
      }
    }
    return { isATag: false, node: parent }
  }
}

export default {
  created(el) {
    el.addEventListener('click', (event: any) => {
      const clickedElement = event.target
      const a = queryTag(clickedElement).node
      const isATag = queryTag(clickedElement).isATag // 判断是不是a标签
      if (!isATag) {
        return // 不是A标签
      }
      const dest_url = a.getAttribute('href') || '' // 需要上报的外链地址是否存在
      if (!dest_url) {
        return // href值为空
      }
      const isEmail = dest_url.startsWith(PrefixEmail) ? emailRegExp.test(dest_url.replaceAll(PrefixEmail, '')) : emailRegExp.test(dest_url) // 判断是不是邮箱
      const noGitCode = hostList.some(url => dest_url.includes(url)) && hrefList.every(url => !dest_url.includes(url)) // 判断是否属于外链

      if (isEmail || noGitCode) {
        useReport('a-tag-click', { dest_url })
      }
    })
  },
} as Directive
